package com.yuwei.image.util

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import java.io.ByteArrayOutputStream

/**
 * 图片压缩处理方式
 * 图片所占内存大小计算公式 图片宽*图片高 * 每个像素所占字节(编码格式)
 * 添加采样后公式 (图片宽/采样率)*(图片高/采用率) * 每个像素所占字节(编码格式)
 */
object BitmapUtil {
    /**
     * 1.质量压缩
     */
    fun compressQualityBitmap(res: Resources,resId: Int,quality: Int): Bitmap{
        val bitmap = BitmapFactory.decodeResource(res, resId)
        val bitmapOs = ByteArrayOutputStream()
        val compress = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bitmapOs)
        return BitmapFactory.decodeByteArray(bitmapOs.toByteArray(),quality,bitmapOs.size())
    }
    /**
     * 2.矩阵压缩
     */
    fun compressMatrixBitmap(res: Resources,resId: Int,width: Float,height: Float): Bitmap{

        val matrix = Matrix().apply {
            setScale(width,height)
        }
        val bitmap = BitmapFactory.decodeResource(res, resId)
        return Bitmap.createBitmap(bitmap,0,0,bitmap.width,bitmap.height,matrix,true)
    }
    /**
     * 3.编解码压缩
     */
    fun compressEncodeFormatBitmap(res: Resources,resId: Int,bitmapConfig: Bitmap.Config = Bitmap.Config.RGB_565): Bitmap{
        val options = BitmapFactory.Options()
        options.inPreferredConfig = bitmapConfig
        return BitmapFactory.decodeResource(res, resId,options)
    }
    /**
     * 4.缩放压缩
     */
    fun compressScaleBitmap(res: Resources,resId: Int,width: Int,height: Int): Bitmap{
        val bitmap = BitmapFactory.decodeResource(res, resId)
        return Bitmap.createScaledBitmap(bitmap,width,height,true)
    }
    /**
     * 5.二次采样压缩
      */
    fun compressSampleBitmap(res: Resources,resId: Int,maxWidth: Int,maxHeight: Int): Bitmap{
        var sampleSize = 1
        //第一次 读取图片的边框大小
        val options = BitmapFactory.Options().apply {
            inJustDecodeBounds = true
        }
        BitmapFactory.decodeResource(res, resId,options)
        //获取图片的大小
        var bitmapWidth = options.outWidth
        var bitmapHeight = options.outHeight
        while (bitmapWidth>maxWidth || bitmapHeight>maxHeight){
            //每次缩小2倍
            sampleSize *= 2
            //重新设置图片大小
            bitmapWidth/=sampleSize
            bitmapHeight/=sampleSize
        }
        //第二次加载图片
        options.inJustDecodeBounds = false //读取图片的像素
        options.inSampleSize = sampleSize
        options.inPreferredConfig = Bitmap.Config.RGB_565 //可选
        return BitmapFactory.decodeResource(res,resId,options)
    }

}